package ipmss.ui.authentication;

import java.io.Serializable;
import java.util.Locale;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.inject.Named;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;

// TODO: Auto-generated Javadoc
/**
 * The Class LoginBean.
 *
 * @author Michał Czarnik
 */
@Named
public class LoginBean implements Serializable
{
 
    /** The authentication manager. */
    private AuthenticationManager authenticationManager;
    
    /** The login. */
    private String login;
    
    /** The password. */
    private String password;
    
    //private final AuthenticationManager am;

 /*   @Inject
    public LoginBean(@Named("authenticationManager") AuthenticationManager am) {
        this.authenticationManager = am;
    }*/



    /**
     * Gets the login.
     *
     * @return the login
     */
    public String getLogin()
    {
	return login;
    }

    /**
     * Sets the login.
     *
     * @param login the new login
     */
    public void setLogin(String login)
    {
	this.login = login;
    }

    /**
     * Gets the password.
     *
     * @return the password
     */
    public String getPassword()
    {
	return password;
    }

    /**
     * Sets the password.
     *
     * @param password the new password
     */
    public void setPassword(String password)
    {
	this.password = password;
    }
    
    /**
     * Authentication.
     *
     * @return the string
     */
    public String authentication()
    {
	/*Authentication request = new UsernamePasswordAuthenticationToken(
		login,password);
	Authentication result = authenticationManager.authenticate(request);
	SecurityContextHolder.getContext().setAuthentication(result);*/
	  try {
	            Authentication request = new UsernamePasswordAuthenticationToken(this.getLogin(), getPassword());
	            Authentication result = authenticationManager.authenticate(request);
	            SecurityContextHolder.getContext().setAuthentication(result);

	        } catch (AuthenticationException e) {
	         /*   String loginFailedMessage = FacesUtils.getBundleKey("msg", "login.failed");
	            FacesUtils.addErrorMessage(loginFailedMessage);*/
	            return null;
	        }

	/* nie dziala
	 * UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
	  viewRoot.setLocale(new Locale("en"));*/
	return "login";
    }
    

}
